package service.impl;

import common.impl.exception.ServiceException;

import model.MRewrite;
import net.sf.json.JSONObject;
import service.interf.IRewrite;
import dao.interf.IRewriteDao;
import dao.pojo.Rewrite;


public class RewriteImpl implements IRewrite{
	private IRewriteDao rewriteDao;

	public void setrewriteDao(IRewriteDao rewriteDao) {
		this.rewriteDao = rewriteDao;
	}


	@Override
	public String add(MRewrite model) {
		Rewrite rewrite = new Rewrite();

		rewrite.setRewriteDirection(model.getRewriteDirection());
		rewrite.setRewriteTitle(model.getRewriteTitle());
		rewrite.setRewriteKeys(model.getRewriteKeys());
		
		return rewriteDao.add(rewrite);
	}

	@Override
	public String getById(MRewrite model) {
		Rewrite rewrite = rewriteDao.getById(model.getRewriteId());
		if(null == rewrite) {
			throw new ServiceException("ERR-0061");
		}
		return createRewriteObj(rewrite).toString();
	}

	@Override
	public String deleteById(Integer id) {
		rewriteDao.deleteById(id);
		return "1";
	}

	@Override
	public String edit(MRewrite model) {
		Rewrite rewrite = rewriteDao.getById(model.getRewriteId());
		if (null == rewrite) {
			throw new ServiceException("ERR-0061");
		}
		
		rewrite.setRewriteDirection(model.getRewriteDirection());
		rewrite.setRewriteTitle(model.getRewriteTitle());
		rewrite.setRewriteKeys(model.getRewriteKeys());
		
		rewriteDao.edit(rewrite);
		return "1";
	}
	
	public JSONObject createRewriteObj(Rewrite rewrite) {
		JSONObject obj = new JSONObject();
		
		obj.put("rewriteId", rewrite.getRewriteId());
		obj.put("rewriteDirection", rewrite.getRewriteDirection());
		obj.put("rewriteTitle", rewrite.getRewriteTitle());
		obj.put("rewrite", rewrite.getRewriteKeys());
		
		return obj;	
	}


}
